import 'dart:async';
import 'dart:ui';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutterlib/common/config/config.dart';
import 'package:flutterlib/common/localization/quhui_localizations_delegate.dart';
import 'package:provider/provider.dart';
import 'package:thrio/thrio.dart';

import 'common/connection/connectivity_store.dart';
import 'common/constants/constants.dart';
import 'common/constants/hive_boxes.dart';
import 'common/datacenter/channel_data_center.dart';
import 'common/provider/themes_provider.dart';
import 'module.dart';
import 'common/utils/utils.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'settings_store.dart';

void main() async {
  trueDebugPrint("flutterting" + "flutterting,flutter main");
  WidgetsFlutterBinding.ensureInitialized();
  final sharedPreferences = await SpUtils().init();
  await Hive.initFlutter();
  await HiveBoxes.openBoxes();
  await DeviceUtils.initDeviceInfo();
  ChannelDataCenter().init();

  runZoned(() {
    ErrorWidget.builder = (FlutterErrorDetails details) {
      Zone.current.handleUncaughtError(details.exception, details.stack);
      return Container(color: Colors.transparent);
    };

    //设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
    runApp(MyApp(sharedPreferences: sharedPreferences));
  }, onError: (Object obj, StackTrace stack) {
    print(obj);
    print(stack);
  });
}

class MyApp extends StatefulWidget {
  final sharedPreferences;
  MyApp({this.sharedPreferences});

  @override
  _MyAppState createState() => _MyAppState();
}

//为app启动时启动，此时获取的shareprefence不全
class _MyAppState extends State<MyApp>{
  ToastFuture connectivityToastFuture;

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      Connectivity().checkConnectivity().then(connectivityHandler);
    });
    ThrioModule.init(Module(), 'main');
    trueDebugPrint("flutterting" + "myappstate initstate");

  }

  void connectivityHandler(ConnectivityResult result) {
    checkIfNoConnectivity(result);
    trueDebugPrint('Current connectivity: $result');
  }

  void checkIfNoConnectivity(ConnectivityResult result) {
    if (result == ConnectivityResult.none) {
      connectivityToastFuture ??= showNoConnectivityDialog;
    } else {
      connectivityToastFuture?.dismiss(showAnim: true);
      if (connectivityToastFuture != null) {
        connectivityToastFuture = null;
      }
    }
  }
  ToastFuture get showNoConnectivityDialog => showToastWidget(
        noConnectivityWidget,
        duration: Duration(hours: 999),
        handleTouch: true,
      );

  Widget get noConnectivityWidget => Material(
        color: Colors.black26,
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 2.0, sigmaY: 2.0),
          child: Center(
            child: Container(
              width: Screens.width / 2,
              height: Screens.width / 2,
              padding: const EdgeInsets.all(20.0),
              decoration: BoxDecoration(
                color: Theme.of(context).canvasColor,
                shape: BoxShape.circle,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Icon(
                    Icons.router,
                    size: Screens.width / 6,
                    color: Theme.of(context).iconTheme.color,
                  ),
                  SizedBox(height: Screens.width / 20),
                  Text(
                    '检查网络连接',
                    style: Theme.of(context)
                        .textTheme
                        .bodyText1
                        .copyWith(fontSize: 20.0),
                  ),
                ],
              ),
            ),
          ),
        ),
      );

  @override
  Widget build(BuildContext context) {
    trueDebugPrint("flutterting" + "myappstate build");
    return MultiProvider(
      providers: [
        Provider<PreferencesService>(
          create: (_) => PreferencesService(widget.sharedPreferences),
        ),
        ProxyProvider<PreferencesService, SettingsStore>(
            update: (_, preferencesService, __) =>
                SettingsStore(preferencesService)),
        Provider<ConnectivityStore>(
          create: (_) => ConnectivityStore(),
          dispose: (_, store) => store.dispose(),
        ),
        buildProvider<ThemesProvider>(ThemesProvider()),
      ],
        child: Consumer2<SettingsStore, ThemesProvider>(
          builder: (BuildContext _,
              SettingsStore store,
              ThemesProvider themesProvider,
              Widget __,) => Observer(
            builder: (_) {
              final bool isDark = false;
              final ThemeData theme =
              (isDark ? themesProvider.darkTheme : themesProvider.lightTheme);
                //   .copyWith(
                // pageTransitionsTheme: const PageTransitionsTheme(
                //   builders: <TargetPlatform, PageTransitionsBuilder>{
                //     TargetPlatform.android: ZoomPageTransitionsBuilder(),
                //   },
                // ),
              // );


              return ExcludeSemantics(
                  child: OKToast(
                    child: NavigatorMaterialApp(
                navigatorKey: Instances.navigatorKey,
              ///多语言实现代理
                localizationsDelegates: [
                    GlobalMaterialLocalizations.delegate,
                    GlobalWidgetsLocalizations.delegate,
                    QuhuiLocalizationsDelegate.delegate,
                ],
                theme: theme,
                supportedLocales: [Locale('zh', 'CH')],
                title: 'quhui',
                // builder: FlutterBoost.init(postPush: _onRoutePushed),
                locale: Locale('zh', 'CH'),
//注册路由表
//                 routes: {
//                   "activity_list_page": (context) => ActivityPage(),
//                   "post_detail_page": (context) => PostDetailPage(),
//                   "/": (context) => HomePage(),
//                 }
              //Text("test", style: TextStyle(
//            fontSize: 16.0,
//            color: const Color.fromARGB(255, 192, 192, 192)),
//        )
                    ),
                  ));
            },
          ),
        ));
  }
//
}

ChangeNotifierProvider<T> buildProvider<T extends ChangeNotifier>(T value) {
  return ChangeNotifierProvider<T>.value(value: value);
}

